<template>
  <div class="page" v-loading.fullscreen.lock="loading">
    <div class="page-panel">
      <div class="fe-page-header">
        <div class="fe-page-header__left">
          {{ title }}
        </div>
        <div class="fe-page-header__right">
          <el-button type="plain-third"  @click="back">{{$t('common.base.cancel')}}</el-button>
          <el-button type="primary" @click="validate" :disabled="pending">{{$t('common.base.save')}}</el-button>
        </div>
      </div>
      <div class="page-panel-body">
        <el-form label-position="top" :model="servicePrice" :rules="rules" ref="partForm">
          <el-form-item :label="`${$t('common.base.name')}：`" prop="name">
            <el-input v-model="servicePrice.name" :placeholder="$t('servicePrice.edit.placeholder1')" maxlength="255"></el-input>
          </el-form-item>
          <el-form-item :label="`${$t('common.form.preview.serviceItem.colum2')}：`" prop="serialNumber">
            <el-input v-model.trim="servicePrice.serialNumber" :placeholder="$t('servicePrice.edit.placeholder2')" maxlength="50"></el-input>
          </el-form-item>
          <el-form-item prop="type">
            <template slot="label">
              {{$t('common.form.preview.serviceItem.colum3')}}：
              <el-tooltip trigger="hover">
                <template slot="content">{{$t('servicePrice.edit.tip1')}}</template>
                <i class="el-icon-question" />
              </el-tooltip>
            </template>
            <el-select v-model="servicePrice.type" :placeholder="$t('servicePrice.edit.placeholder3')">
              <el-option :label="item" :value="item" v-for="item in types" :key="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="unit">
            <template slot="label">
              {{$t('common.form.preview.serviceItem.colum4')}}：
              <el-tooltip trigger="hover">
                <template slot="content">{{$t('servicePrice.edit.tip2')}}</template>
                <i class="el-icon-question" />
              </el-tooltip>
            </template>
            <el-select v-model="servicePrice.unit" :placeholder="$t('servicePrice.edit.placeholder4')">
              <el-option :label="item" :value="item" v-for="item in units" :key="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="`${$t('servicePrice.list.displayName.salePrice')}：`" prop="salePrice" class="form-content-flex">
            <el-input class="w-667" v-model.number="servicePrice.salePrice" @blur="numeric('salePrice', $event)" @input="filterNumber($event, 'salePrice')" :placeholder="$t('servicePrice.edit.placeholder5')" maxlength='8'></el-input>
            <el-select v-if="internationalGray" class='w-33' v-model="servicePrice.salePriceCurrency" :placeholder="$t('common.placeholder.select')">
              <el-option
                v-for="item in currencyOption"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="`${$t('servicePrice.list.displayName.deliveryPrice')}：`" prop="costPrice" class="form-content-flex">
            <el-input class="w-667" v-model.number="servicePrice.costPrice" @blur="numeric('costPrice', $event)" @input="filterNumber($event, 'costPrice')" :placeholder="$t('servicePrice.edit.placeholder6')" maxlength='8'></el-input>
            <el-select v-if="internationalGray" class='w-33' v-model="servicePrice.costPriceCurrency" :placeholder="$t('common.placeholder.select')">
              <el-option
                v-for="item in currencyOption"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item :label="`${$t('common.label.ralationProductType')}：`" prop="productTypeList">
            <el-cascader
              :placeholder="$t('common.placeholder.selectProductType')"
              popperClass="cascader-checkbox"
              v-model="catalogPathIds"
              :options="catalogOption"
              :show-all-levels="false"
              expand-trigger="hover"
              clearable
              :props="catalogCascaderProps"
              filterable
              collapse-tags
            ></el-cascader>
          </el-form-item>
          <el-form-item :label="`${$t('common.base.image')}：`" class="category-edit-form-item-upload">
            <base-upload :value="attachments" @input="uploadImg" :limit="1" accept="image/*">
              <template slot="preview">
                <div class="servicePrice-image-preview" v-show="servicePriceImg">
                  <img :src="servicePriceImg" @click="preview(servicePriceImg)">
                  <button type="button" @click.stop="removeServicePriceImg" class="servicePrice-image-close"><i class="el-icon-circle-close"></i></button>
                </div>
              </template>
            </base-upload>
          </el-form-item>
        </el-form>
      </div>
    </div>  
  </div>
</template>

<script>
// api
import * as ServicePriceApi from '@src/api/ServicePriceApi';
import { cloneData } from '@src/api/ProductV2Api';
import _ from 'lodash';
/* enum */
import TenantDataLimitSourceEnum from '@model/enum/TenantDataLimitSourceEnum'
import TenantDataLimitTypeEnum from '@model/enum/TenantDataLimitTypeEnum'
/* mixin */
import VersionMixin from '@src/mixins/versionMixin/index.ts'
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
import { RESOURCE_PREFIX } from '@src/util/linkSwitch'
import i18n from '@src/locales';
import { currencyOption } from '@src/util/currency'
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()
import { parse } from '@src/util/querystring';
import { openAccurateTab } from '@src/util/platform'

export default {
  name: 'service-price-edit-view',
  mixins: [VersionMixin, ThemeMixin],
  data() {
    return {
      internationalGray,
      action: 'edit',
      title: '',
      units: [],
      types: [],
      serviceConfig: {},
      pending: false,
      loading: false,
      attachments: [],

      origin: {},
      
      servicePrice: {
        id: '',
        serialNumber: '',
        name: '',
        type: '',
        unit: '',
        salePrice: '',
        costPrice: '',
        logoUrl: '',
        catalogIds: [],
        salePriceCurrency: 'CNY',
        costPriceCurrency: 'CNY'
      },
      catalogPathIds: [],
      rules: {
        serialNumber: [
          {required: false, message: i18n.t('servicePrice.edit.tip3'), trigger:'change'}, // serviceConfig.numberDuplicate判断是否需要required
          {max: 50, message: i18n.t('servicePrice.edit.tip4'), trigger:'change'}
        ],
        name: [
          {required: true, message: i18n.t('servicePrice.edit.tip5')},
          {max: 255, message: i18n.t('servicePrice.edit.tip6')}
        ],
        salePrice: [
          {
            validator(rule, value, callback) {
              const val = Number(value);
              if (value === '') {
                callback(new Error(i18n.t('servicePrice.edit.tip7')))
              } else if(val < 0 || isNaN(val)){
                callback(new Error(i18n.t('servicePrice.edit.tip8')))
              } else{
                callback();
              }
            },
            trigger: 'change',
            required: true
          }
        ],
        costPrice: [
          {
            validator(rule, value, callback) {
              const val = Number(value);
              if (value === '') {
                callback(new Error(i18n.t('servicePrice.edit.tip9')))
              } else if(val < 0 || isNaN(val)){
                callback(new Error(i18n.t('servicePrice.edit.tip10')))
              } else{
                callback();
              }
            },
            trigger: 'change',
            required: true
          }
        ]  
      },
      catalogOption: [],
      catalogCascaderProps: {
        multiple: true,
        value: 'id',
        label: 'name',
        children: 'tasks',
      },
      currencyOption
    }; 
  },
  computed: {
    servicePriceImg(){
      if(!this.attachments || this.attachments.length == 0) return null;

      if(Array.isArray(this.attachments) && this.attachments.length > 0) {
        return this.attachments.map(item => item.url);
      }else {
        return this.attachments[0].url;
      }
    }
  },
  methods: {
    preview(url){
      this.$previewElementImg(url)
      // BaseGallery.preview(event.target)
    },

    uploadImg(attachments){
      this.attachments = attachments;
    },

    async removeServicePriceImg(){
      if(await this.$platform.confirm(this.$t('servicePrice.edit.tip11'))) this.attachments = [];
    },

    numeric(field, event){
      let value = this.servicePrice[field];
      this.servicePrice[field] = '';
      this.$nextTick(() => this.servicePrice[field] = value);
    },

    filterNumber(value, field) {
      if(!value) return;
      let reg = /^[0-9]+([.]{1}[0-9]{0,2}){0,1}$/;
      let num = reg.test(value) ? value : (isNaN(Number(value)) ? '' : Number(value).toFixed(3).slice(0, -1));
      this.$nextTick(() => this.servicePrice[field] = num);
    },

    validate() {
      if(this.pending) return;

      this.pending = true; 

      this.$refs.partForm.validate((valid) => {
        if(valid) {
          this.submit(this.servicePrice)
        } else {
          this.pending = false;
        }
      })
    },

    back(){
      let query = parse(window.location.search) || {};
      if (query.from == 'list' || this.action == 'create') {
        let id = window.frameElement.dataset.id;
        return this.$platform.closeTab(id)
      }
      parent.frameHistoryBack(window)
    },

    async submit(servicePrice){
      this.pending = true;

      servicePrice.catalogIds = this.catalogPathIds?.map(item => item[item.length - 1]) || [];
      try {
        if(this.servicePriceImg) {
          servicePrice.logoUrl = this.servicePriceImg.join('')
        }
        
        const isEdit = this.action == 'edit'
        const url = isEdit ? '/service/price/update' : '/service/price/create';
        let fetchPromise = this.$http.post(url, servicePrice)
        
        if (!isEdit) {
          fetchPromise = this.checkNumExceedLimitAfterHandler(fetchPromise)
        }
        
        const result = await fetchPromise

        if(result.status == 0){
          let fromId = window.frameElement.getAttribute('fromid')
          !isEdit && this.$platform.refreshTab(fromId)

          this.$platform.closeTab(window.frameElement.dataset.id)
          openAccurateTab({
            type: PageRoutesTypeEnum.PageServicePriceDetailView,
            key: result.data.id,
            fromId: window.frameElement.getAttribute('id')
          })
        } else if( result.status == 2 ) {
          // openVersionLimitDialog
        } else {
          this.$platform.alert(result.message)
        }
      } catch (error) {
        console.warn(error)
      }

      this.pending = false;
    },

    initialize(origin){
      let servicePrice = this.servicePrice;

      servicePrice.id = origin.id || '';
      servicePrice.serialNumber = origin.serialNumber || '';
      servicePrice.name = origin.name || ''
      servicePrice.type = origin.type || '';
      servicePrice.unit = origin.unit || '';
      servicePrice.salePrice = origin.id ? origin.salePrice : '';
      servicePrice.costPrice = origin.id ? origin.costPrice : '';
      servicePrice.salePriceCurrency = origin.id ? origin?.salePriceCurrency : 'CNY';
      servicePrice.costPriceCurrency = origin.id ? origin?.costPriceCurrency : 'CNY';
      servicePrice.catalogIds = origin.catalogIds;
      
      this.catalogPathIds = origin.catalogPathIds || [];

      if(origin.logoUrl){
        this.attachments = [{
          url: origin.logoUrl
        }]
      }

      if(this.units.length > 0 && !origin.unit) servicePrice.unit = this.units[0]; 
      if(this.types.length > 0 && !origin.type) servicePrice.type = this.types[0]; 
    },

    fetchData(id){
      if(!id) {
        this.loading = false
        return Promise.all({})
      }

      return ServicePriceApi.servicePriceDetailById({id})
    },

    numberDuplicateSerialNumber() {
      const serialNumberRules = [
        {required: true, message: this.$t('servicePrice.edit.tip3'), trigger:'change'}, // serviceConfig.numberDuplicate判断是否需要required
        {max: 50, message: this.$t('servicePrice.edit.tip4'), trigger:'change'},
        {validator: _.debounce((rule, value, callback) => {
          value = value && value.trim();
          
          let err = [];
          if(this.action == 'edit' && value == this.origin.serialNumber) return callback(err)
          const params = {
            serialNumber: value,
            type: this.action == 'edit' ? 'edit' : 'add',
            servicePriceId: this.action == 'edit' ? this.servicePrice.id : ''
          }
          ServicePriceApi.servicePriceCheckNumberDuplicate(params)
            .then(result => {
              // TODO 中文判断改成errorCode
              if(Number(result.errorCode) === 2016) err.push(new Error(this.$t('servicePrice.edit.tip12')))
            })
            .catch(err => console.warn(err))
            .finally(() => callback(err))
        }, 500)}
      ]
      this.$set(this.rules, 'serialNumber', serialNumberRules)
    },

    // 获取树结构
    async getCatalogOption() {
      try {
        const catalogId = (this.catalogPathIds.map(item => item[item.length - 1]) || []).join(',');
        let { code, result, message } = await cloneData({catalogId: catalogId || ''});
        if (code === 0) {
          this.deleteEmpty(result);
          this.catalogOption = result;
        } else {
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.tip.httpIsError'),
            message: message,
          });
        }
      } catch (err) {
        console.error(err);
      }
    },

    // 删除空子集
    deleteEmpty(list) {
      list.forEach(item => {
        if (!item.tasks.length) {
          delete item.tasks;
        } else {
          this.deleteEmpty(item.tasks);
        }
      });
    },
  },

  async mounted(){

    try {
      let path = window.location.pathname;
      if(path.indexOf(RESOURCE_PREFIX) > -1) path = path.replace(RESOURCE_PREFIX, '')
      if(path == '/service/price/createView/0') {
        this.action = 'create'
        document.title = this.$t('common.pageTitle.pageServicePriceCreateView')
        this.title = this.$t('common.pageTitle.pageServicePriceCreateView')
      } else {
        this.action = 'edit'
        document.title = this.$t('common.pageTitle.pageServicePriceView')
        this.title = this.$t('common.pageTitle.pageServicePriceView')
      }

      const id = this.action === 'edit' ? path.split('/service/price/edit/')[1] : ''

      const editInfo = await ServicePriceApi.servicePriceEditInfo({id})
      const {serviceConfig, serviceItem } = editInfo.data
      this.units = serviceConfig.serviceUnit || [];
      this.types = serviceConfig.serviceItemsType || [];
      this.serviceConfig = serviceConfig

      if(serviceConfig.numberDuplicate) {
        this.numberDuplicateSerialNumber()
      }

      let servicePrice = {};

      if(this.action == 'edit'){
        this.loading = true
        const result = await this.fetchData(id);
        this.loading = false
        servicePrice = result.data || {};
      } else {
        // 检查版本数量限制
        this.checkNumExceedLimitBeforeHandler
        && this.checkNumExceedLimitBeforeHandler(
          TenantDataLimitSourceEnum.Service,
          TenantDataLimitTypeEnum.Service
        )
      }

      this.initialize(servicePrice);
      this.origin = servicePrice;
      this.getCatalogOption();
    } catch (error) {
      console.warn(error)
    }
  }          
}
</script>

<style lang="scss" scoped>
.is-required:before {
  content: '';
}
.servicePrice-image-preview{
  position: relative;
  width: 128px;
  max-height: 128px;
  cursor: pointer;
  overflow: hidden;

  img{
    display: block;
    max-width: 100%;
    max-height: 100%;
  }

  .servicePrice-image-close{
    position: absolute;
    top: 5px;
    right: 5px;
    border: none;
    outline: none;
    background-color: transparent;
    padding: 0;
    cursor: pointer;

    color: #F56C6C;
    font-size: 16px;
    display: none;
  }

  &:hover{
    .servicePrice-image-close{
      display: block;
    }
  }
}

.category-edit-form-item-upload {
  margin-top: 10px;
}
.el-cascader {
  width: 100%;
}
.page {
  height: 100%;
}
.page-panel-body {
  height: calc(100% - 56px);
  overflow: auto;
}
.page-panel {
  margin-bottom: 0;
  height: 100%;
  overflow: hidden;
}
.el-form {
  max-width: 824px;
  margin: 0 auto;
}
.el-form-item {
  margin-bottom: 17px;
}
.form-head {
  height: 56px;
  box-shadow: 0px 1px 0px 0px #F4F7F5;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  .form-head-title {
    font-weight: bold;
    color: #262626;
    font-size: 16px;
  }
}

::v-deep .form-content-flex .el-form-item__content {
  flex: 1;
  display: flex;
}

.w-667 {
  width: 66.6666667% !important;
}
.w-33 {
  width: 140px !important;
  margin-left: 10px;
}
.price-style {
  display: flex;
  
}
</style>
